package com.luli.config.websocketConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 陆离
 * 2024/6/2 13:41:28
 */
@Slf4j
public class SessionPool {

    public static Map<String, Session> sessions = new ConcurrentHashMap<>();


    public static void close(String sessionId) throws IOException {
        for (String userId : SessionPool.sessions.keySet()) {
            Session session = SessionPool.sessions.get(userId);
            if (session.getId().equals(sessionId)) {
                sessions.remove(userId);
                break;
            }
        }
    }

    /**
     * 发送指定一个
     *
     * @param sessionId
     * @param message
     */
    public static void senMessage(String sessionId, String message) {
        log.info("消息--->" + message);
        SessionPool.sessions.get(sessionId).getAsyncRemote().sendText(message);
    }

    /**
     * 发送全部
     *
     * @param message
     */
    public static void senMessage(String message) {
        JSONObject param = JSONObject.parseObject(message);
        List<Object> fromUserId = objToList(param.get("fromUserId"));
        //发送至全部
        if (CollectionUtils.isEmpty(fromUserId)) {
            for (String sessionId : SessionPool.sessions.keySet()) {
                SessionPool.sessions.get(sessionId).getAsyncRemote().sendText((String) param.get("message"));
            }
        }else {
            //发送指定用户
            for (String sessionId : SessionPool.sessions.keySet()) {
                for (Object s : fromUserId) {
                    if (sessionId.equals(s)) {
                        //发送到当前的会话
                        SessionPool.sessions.get(sessionId).getAsyncRemote().sendText((String) param.get("message"));
                    }
                }
            }
        }

    }


    public static List<Object> objToList(Object obj) {
        List<Object> list = new ArrayList<Object>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                list.add(o);
            }
            return list;
        }
        return null;
    }
}
